package com.qqtech.qquan.user.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.sys.controller.BaseAdminController;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.sys.model.SysParam;
import com.qqtech.qquan.sys.service.SysParamService;
import com.qqtech.qquan.user.enums.UserConst;
import com.qqtech.qquan.user.enums.UserWithdrawStatusDictEnum;
import com.qqtech.qquan.user.model.UserValueVo;
import com.qqtech.qquan.user.model.UserWithdraw;
import com.qqtech.qquan.user.model.UserWithdrawQuery;
import com.qqtech.qquan.user.model.UserWithdrawVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserSysDictService;
import com.qqtech.qquan.user.service.UserValueService;
import com.qqtech.qquan.user.service.UserWithdrawService;
import com.qqtech.qquan.util.ExcelUtil;

@Controller
@RequestMapping(value = "/user/withdraw")
public class UserWithdrawController extends BaseAdminController {

	@Resource
	private UserWithdrawService userWithdrawService;

	@Resource
	private UserSysDictService userSysDictService;
	@Resource
	private UserValueService userValueService;
	@Resource
	private UserBaseService userBaseService;
	@Resource
	private SysParamService sysParamService;

	@Override
	protected BaseService<UserWithdraw> getBaseService() {
		return userWithdrawService;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		UserWithdrawQuery query = new UserWithdrawQuery();
		query.setStatus(UserWithdrawStatusDictEnum.FINISHED.getCode());
		BigDecimal allSum = userWithdrawService.querySumCash(query);//全汇总
		
		query.setStartAt(TimeUtil.yearStartDay());
		query.setEndAt(TimeUtil.now());
		BigDecimal yearSum = userWithdrawService.querySumCash(query);//当年汇总
		
		query.setStartAt(TimeUtil.monthStartDay());
		query.setEndAt(TimeUtil.now());
		BigDecimal mothSum = userWithdrawService.querySumCash(query);//当月汇总
		
		model.addAttribute("allSum", allSum==null ? 0.00 : allSum);
		model.addAttribute("yearSum", yearSum==null ? 0.00 : yearSum);
		model.addAttribute("mothSum", mothSum==null ? 0.00 : mothSum);
		return "/user/withdraw/userwithdraw-list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(UserWithdrawQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.ASC, "status"),
				new PageOrder(Direction.DESC, "id"));
		Page<UserWithdrawVo> page = userWithdrawService.queryPageListAdmin(query, pageKit);
		String typeDesc = null;
		for (UserWithdrawVo userWithdrawVo : page) {
			typeDesc = userSysDictService.dictValue(UserConst.DICTYPE_USER_WITHDRAW_TYPE,
					String.valueOf(userWithdrawVo.getType()));
			userWithdrawVo.setTypeDesc(typeDesc);
			userWithdrawVo.setStatusDesc(userSysDictService.dictValue(UserConst.DICTYPE_USER_WITHDRAW_STATUS,
					String.valueOf(userWithdrawVo.getStatus())));
			userWithdrawVo.setFlowId(userWithdrawVo.getId());
		}
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	/**
	 * 确认
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/confirm", method = RequestMethod.POST)
	@ResponseBody
	public Result confirm(Integer id) {
		Result ret = new Result();
		UserWithdraw userWithdraw = userWithdrawService.getById(id);
		UserValueVo userValueVo = userValueService.getById(userWithdraw.getUserId());
		Integer totalCash = userWithdraw.getCash().intValue() * 100;
		if (userValueVo.getMoney() < totalCash) {
			ret.addErr("用户余额不足提现。");
			return ret;
		}
		userWithdrawService.handleConfirm(id);
		return ret;
	}

	/**
	 * 取消
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/cancle", method = RequestMethod.POST)
	@ResponseBody
	public Result cancle(Integer id, String remark) {
		Result ret = new Result();
		userWithdrawService.handleCancle(id, remark);
		return ret;
	}

	/**
	 * 确定付款
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/paying", method = RequestMethod.POST)
	@ResponseBody
	public Result paying(Integer id) {
		Result ret = new Result();
		UserWithdraw userWithdraw = userWithdrawService.getById(id);
		UserValueVo userValueVo = userValueService.getById(userWithdraw.getUserId());
		Integer totalCash = userWithdraw.getCash().intValue() * 100;
		if (userValueVo.getMoney() < totalCash) {
			ret.addErr("用户余额不足提现。");
			return ret;
		}
		userWithdraw.setStatus(UserWithdrawStatusDictEnum.PAYING.getCode());
		userWithdrawService.updateById(userWithdraw);
		return ret;
	}

	/**
	 * @param query
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/export2Excel")
	@ResponseBody
	public Result export2Excel(UserWithdrawQuery query, HttpServletRequest request, HttpServletResponse response) {
		Result ret = new Result();
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "newAt"));
		int count = userWithdrawService.queryCount(query);
		SysParam sysParam = sysParamService.getByKey(SysConst.PARAM_SYS_EXPORT_TOEXCEL_MAXROWS);
		if (sysParam != null && StringUtil.isNotBlank(sysParam.getValue())) {
			int maxExportRows = Integer.valueOf(sysParam.getValue());
			if (count > maxExportRows) {
				ret.addErr("导出数量不能超过" + maxExportRows + "行!");
				return ret;
			}
		}
		List<UserWithdrawVo> userWithdrawList = userWithdrawService.queryList4Excel(query, pageKit);// 不分页
		if (userWithdrawList != null && userWithdrawList.size() > 0) {
			for (UserWithdrawVo userWithdrawVo : userWithdrawList) {
				userWithdrawVo.setTypeDesc(userSysDictService.dictValue(UserConst.DICTYPE_USER_WITHDRAW_TYPE,
						String.valueOf(userWithdrawVo.getType())));
				userWithdrawVo.setStatusDesc(userSysDictService.dictValue(UserConst.DICTYPE_USER_WITHDRAW_STATUS,
						String.valueOf(userWithdrawVo.getStatus())));
				userWithdrawVo.setFlowId(userWithdrawVo.getId());
			}
		}

		List<Map<String, Object>> list = createExcelRecord(userWithdrawList);
		String columnNames[] = { "流水号", "用户", "金额", "银行类型", "银行卡号或支付宝账户或微信账户", "开户人姓名", "用户开户行名称", "提现申请状态" };// 列名
		String keys[] = { "flowId", "nick", "cash", "typeDesc", "accountNo", "userReal", "bankName", "statusDesc" };// map中的key
		String fileName = "用户提现表";
		ExcelUtil.ExcelSingleOutputStream(list, keys, columnNames, fileName, request, response);
		return ret;
	}

	private List<Map<String, Object>> createExcelRecord(List<UserWithdrawVo> userWithdrawList) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "用户提现表");
		listmap.add(map);
		UserWithdrawVo userWithdrawVo = null;
		for (int j = 0; j < userWithdrawList.size(); j++) {
			userWithdrawVo = userWithdrawList.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("flowId", userWithdrawVo.getFlowId());
			mapValue.put("nick", userWithdrawVo.getNick());
			mapValue.put("cash", userWithdrawVo.getCash());
			mapValue.put("typeDesc", userWithdrawVo.getTypeDesc());
			mapValue.put("accountNo", userWithdrawVo.getAccountNo());
			mapValue.put("userReal", userWithdrawVo.getUserReal());
			mapValue.put("bankName", userWithdrawVo.getBankName());
			mapValue.put("statusDesc", userWithdrawVo.getStatusDesc());
			listmap.add(mapValue);
		}
		return listmap;
	}
}
